package cn.gs.algorithm.graph;

// @author gs
import java.util.ArrayList;

public class SubTree<T> extends ArrayList<SubTree<T>> {

    public SubTree() {
    }

    public SubTree(T t) {
        this.root = t;
    }
    T root;

    public SubTree<T> getNoException(int index) {
        if (index >= 0 && index < this.size()) {
            return this.get(index);
        } else {
            return null;
        }
    }

    public boolean isLeaf() {
        return isEmpty();
    }

    public SubTree<T> copy() {
        SubTree<T> sub = new SubTree<T>(root);
        for (SubTree<T> t : this) {
            sub.add(t.copy());
        }
        return sub;
    }

    public SubTree<T> recursiveAdd(T[] nodes, int[] count) {
        SubTree<T> t = recursiveAdd(nodes, count, 0);
        add(t);
        return t;
    }

    private SubTree<T> recursiveAdd(T[] nodes, int[] count, int index) {
        SubTree<T> t = new SubTree<T>(nodes[index]);
        for (int i = 1; i <= count[index]; ++i) {
            SubTree<T> s = recursiveAdd(nodes, count, index + i);
            t.add(s);
        }
        return t;
    }
}
